<?php
namespace control;
/*
*报餐取餐统计类
*/


use JetBrains\PhpStorm\NoReturn;

class mealStatisticsClass extends adIndexClass
{
    private const title = '报餐取餐统计';
    private const page = 'mealStatistics';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'peopleSearch':
                $tr = [
                    'department'          => [
                        'name'  => '部门',
                        'width' => 200,
                    ],
                    'staffId' => [
                        'name'  => "员工",
                        'width' => 200,
                    ],
                    'hall'  => [
                        'name'  => "食堂名称",
                        'width' => 200,
                    ],
                    'mealType'         => [
                        'name'  => '餐别',
                        'width' => 200,
                    ],
                    'staffMealNum'          => [
                        'name'  => '报餐份数',
                        'width' => 200,
                    ],
                    'staffGetMealNum'          => [
                        'name'  => '取餐份数',
                        'width' => 200,
                    ],
                    'diff'          => [
                        'name'  => '差异份数',
                        'width' => 300,
                    ]
                ];
                break;
            case 'foodSearch':
                $tr = [
                    'hall'          => [
                        'name'  => '食堂名称',
                        'width' => 200,
                    ],
                    'mealType' => [
                        'name'  => "餐别",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'staffMealNum'  => [
                        'name'  => "员工报餐份数",
                        'width' => 200,
                    ],
                    'staffGetMealNum'         => [
                        'name'  => '员工取餐份数',
                        'width' => 300,
                    ],
                    'visitMealNum'          => [
                        'name'  => '客餐申请份数',
                        'width' => 300,
                    ],
                    'visitGetMealNum'          => [
                        'name'  => '客餐取餐份数',
                        'width' => 300,
                    ]
                ];
                break;
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => '日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'hall'          => [
                        'name'  => '食堂名称',
                        'width' => 200,
                    ],
                    'mealType' => [
                        'name'  => "餐别",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'staffMealNum'  => [
                        'name'  => "员工报餐份数",
                        'width' => 200,
                    ],
                    'menuMx'  => [
                        'name'  => "菜品明细",
                        'width' => 200,
                    ],
                    'staffGetMealNum'         => [
                        'name'  => '员工取餐份数',
                        'width' => 200,
                    ],
                    'visitMealNum'          => [
                        'name'  => '客餐申请份数',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'visitGetMealNum'          => [
                        'name'  => '客餐取餐份数',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "食堂名称" => selectMultiple(array("name" => "hallId", 'table' => "dining_hall", 'sqlId' => 'id', 'sqlField' => 'name', "class" => "width200")),
                    "餐别"     => select(array("name" => "mealType", "option" => explode("，", para("mealOption")))),
                    '日期' => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*客户列表-查询条件*/
    public function home($workFlow = '报餐取餐'): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',exportFun:'exportHomeData',classify:'报餐取餐统计'})\">导出</span>";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
        );
        //全等查询数组
        $equal = array(
            "hallId" => $this->post('hallId'),//公文种类
            "mealType" => $this->post('mealType'),
        );

        $and = " and 1=1";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "recordDate");
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => "meal_report",
            "where" => $where." group by recordDate,hallId,mealType",
            'field'=>"recordDate,hallId,mealType",
            "order" => $orderBy['orderBy']
        ));
        static::rSet(self::$stid.self::page.'homeSql', $page['fullSql'], 3600*5); // 设置redis
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&source=报餐取餐&recordDate={$array['recordDate']}&hallId={$array['hallId']}&mealType={$array['mealType']}')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "hall":
                        $hall = query('dining_hall',"id = '$array[hallId]'");
                        $row[] = $hall['name'];
                        break;
                    case "staffMealNum":
                        $staffMealNum = find(array('table'=>'meal_report','where'=>"hallId = '$array[hallId]' and recordDate = '$array[recordDate]' and mealType = '$array[mealType]' and type in ('报餐','代报餐')",'sum'=>'num'));
                        $row[] = $staffMealNum;
                        break;
                    case "menuMx":
                        $row[] = $this->getMenuMx($array);
                        break;
                    case "staffGetMealNum":
                        $staffGetMealNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$array[hallId]' and recordDate = '$array[recordDate]' and mealType = '$array[mealType]' and type in ('取餐','代取餐')",'sum'=>'num'));
                        $row[] = $staffGetMealNum;
                        break;
                    case "visitMealNum":
                        $visitMealNum = find(array('table'=>'meal_report','where'=>"hallId = '$array[hallId]' and recordDate = '$array[recordDate]' and mealType = '$array[mealType]' and type ='申请客餐'",'sum'=>'num'));
                        $row[] = $visitMealNum;
                        break;
                    case "visitGetMealNum":
                        $visitGetMealNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$array[hallId]' and recordDate = '$array[recordDate]' and mealType = '$array[mealType]' and type ='客餐取餐'",'sum'=>'num'));
                        $row[] = $visitGetMealNum;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] .$button . "<form name='listForm'>" . $li . "</form>" .  $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 导出
     */
    public function exportHomeData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = [];
            }else{
                $sql = static::rGet(self::$stid.self::page.'homeSql');
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $staffMealNum = find(array('table'=>'meal_report','where'=>"hallId = '$array[hallId]' and recordDate = '$array[recordDate]' and mealType = '$array[mealType]' and type in ('报餐','代报餐')",'sum'=>'num'));
                $staffGetMealNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$array[hallId]' and recordDate = '$array[recordDate]' and mealType = '$array[mealType]' and type in ('取餐','代取餐')",'sum'=>'num'));
                $visitMealNum = find(array('table'=>'meal_report','where'=>"hallId = '$array[hallId]' and recordDate = '$array[recordDate]' and mealType = '$array[mealType]' and type ='申请客餐'",'sum'=>'num'));
                $visitGetMealNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$array[hallId]' and recordDate = '$array[recordDate]' and mealType = '$array[mealType]' and type ='客餐取餐'",'sum'=>'num'));
                $hall = query('dining_hall',"id = '$array[hallId]'");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '日期'=>$array['recordDate'],
                            '食堂名称'=>$hall['name'],
                            '餐别'=>$array['mealType'],
                            '员工报餐份数'=>$staffMealNum,
                            '菜品明细'=>$this->getMenuMx($array),
                            '员工取餐份数'=>$staffGetMealNum,
                            '客餐申请份数'=>$visitMealNum,
                            '客餐取餐份数'=>$visitGetMealNum,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了报餐取餐记录";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "报餐取餐记录.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
    /**
     * 获取菜品明细
     */
    public function getMenuMx($array): string
    {
        $str = '';
        $menuMx = find(array('table'=>"meal_report_detail as a join meal_report as b on a.orderId = b.id join dining_menu as c on a.menuId = c.id","where"=>" b.recordDate= '$array[recordDate]' and b.hallId = '$array[hallId]' and b.mealType = '$array[mealType]' and b.type in ('报餐','代报餐') group by recordDate,hallId,mealType,menuId",'field'=>"any_value(c.name) as menuName,ifnull(sum(any_value(a.num)),0) as totalNum"));
        foreach ($menuMx['array'] as $array){
            $str.=$array['menuName'].':'.$array['totalNum'].';';
        }
        return $str;
    }

    /*列表页-查询条件*/
    public function peopleOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "员工" => selectMultiple(array("name" => "staffId", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', "class" => "width200")),
                    "部门"     => selectMultiple(array("name" => "departmentId", 'table' => "department", 'sqlId' => 'id', 'sqlField' => 'name', "class" => "width200")),
                    '食堂名称' => selectMultiple(array("name" => "hallId", 'table' => "dining_hall", 'sqlId' => 'id', 'sqlField' => 'name', "class" => "width200")),
                ],
                [
                    "餐别" => select(array("name" => "mealType", "option" => explode("，", para("mealOption")))),
                    '日期' => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 按人汇总
     *
     */
    public function people(): bool|string
    {
        $html = $this->peopleOptions(false);
        //控件
        $button = "";
        if ($this->power('peopleStatistics', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',exportFun:'exportPeopleData',classify:'按人汇总'})\">导出</span>";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 按人汇总
     * @return bool|string
     */
    public function peopleSearch(): bool|string
    {
        //like查询数组
        $like = array(
        );
        //全等查询数组
        $equal = array(
            "hallId" => $this->post('hallId'),//公文种类
            "mealType" => $this->post('mealType'),
            "departmentId" => $this->post('departmentId'),
            "staffId" => $this->post('staffId'),
        );

        $and = " and 1=1";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "recordDate");
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'staffId',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => "meal_report",
            "where" => $where." group by staffId,hallId,mealType",
            'field'=>"staffId,hallId,mealType",
            "order" => $orderBy['orderBy']
        ));
        static::rSet(self::$stid.self::page.'peopleSql', $page['fullSql'], 3600*5);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&source=按人汇总&staffId={$array['staffId']}&hallId={$array['hallId']}&mealType={$array['mealType']}')"),
            );
            $liButton[] = $this->dominate($dominate);
            $staffMealNum = find(array('table'=>'meal_report','where'=>"hallId = '$array[hallId]' and staffId = '$array[staffId]' and mealType = '$array[mealType]' and type in ('报餐','代报餐')",'sum'=>'num'));
            $staffGetMealNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$array[hallId]' and staffId = '$array[staffId]' and mealType = '$array[mealType]' and type in ('取餐','代取餐')",'sum'=>'num'));

            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "department":
                        $row[] = self::findStaffDepartment($array['staffId']);
                        break;
                    case "staffId":
                        $row[] = self::findStaff($array['staffId']);
                        break;
                    case "hall":
                        $hall = query('dining_hall',"id = '$array[hallId]'");
                        $row[] = $hall['name'];
                        break;
                    case "staffMealNum":
                        $row[] = $staffMealNum;
                        break;
                    case "staffGetMealNum":
                        $row[] = $staffGetMealNum;
                        break;
                    case "diff":
                        $row[] = $staffMealNum-$staffGetMealNum;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='abolishedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 导出
     */
    public function exportPeopleData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power('peopleStatistics', 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }   else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = [];
            }else{
                $sql = static::rGet(self::$stid.self::page.'peopleSql');
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $hall = query('dining_hall',"id = '$array[hallId]'");
                $staffMealNum = find(array('table'=>'meal_report','where'=>"hallId = '$array[hallId]' and staffId = '$array[staffId]' and mealType = '$array[mealType]' and type in ('报餐','代报餐')",'sum'=>'num'));
                $staffGetMealNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$array[hallId]' and staffId = '$array[staffId]' and mealType = '$array[mealType]' and type in ('取餐','代取餐')",'sum'=>'num'));
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '部门'=>self::findStaffDepartment($array['staffId']),
                            '员工'=>self::findStaff($array['staffId']),
                            '食堂名称'=>$hall['name'],
                            '餐别'=>$array['mealType'],
                            '报餐份数'=>$staffMealNum,
                            '取餐份数'=>$staffGetMealNum,
                            '差异份数'=>$staffMealNum-$staffGetMealNum,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了按人汇总报餐取餐记录";
            $this->logText(["type" => 'peopleStatistics', "text" => $text]);
            $this->excelOut($title, $data, "按人汇总报餐取餐记录.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*列表页-查询条件*/
    public function foodOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '食堂名称' => selectMultiple(array("name" => "hallId", 'table' => "dining_hall", 'sqlId' => 'id', 'sqlField' => 'name', "class" => "width200")),

                    "餐别" => select(array("name" => "mealType", "option" => explode("，", para("mealOption")))),
                    '日期' => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 按餐汇总
     *
     */
    public function food(): bool|string
    {
        $html = $this->foodOptions(false);
        //控件
        $button = "";
        if ($this->power('foodStatistics', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',exportFun:'exportFoodData',classify:'按餐汇总'})\">导出</span>";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 按餐汇总
     * @return bool|string
     */
    public function foodSearch(): bool|string
    {
        //like查询数组
        $like = array(
        );
        //全等查询数组
        $equal = array(
            "hallId" => $this->post('hallId'),//公文种类
            "mealType" => $this->post('mealType'),
        );

        $and = " and 1=1";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "recordDate");
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'hallId',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => "meal_report","where" => $where." group by hallId,mealType", 'field'=>"hallId,mealType","order" => $orderBy['orderBy']));
        static::rSet(self::$stid.self::page.'foodSql', $page['fullSql'], 3600*5); // 设置redis
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&source=按餐汇总&hallId={$array['hallId']}&mealType={$array['mealType']}')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "hall":
                        $hall = query('dining_hall',"id = '$array[hallId]'");
                        $row[] = $hall['name'];
                        break;
                    case "staffMealNum":
                        $staffMealNum = find(array('table'=>'meal_report','where'=>"hallId = '$array[hallId]' and mealType = '$array[mealType]' and type in ('报餐','代报餐')",'sum'=>'num'));
                        $row[] = $staffMealNum;
                        break;
                    case "staffGetMealNum":
                        $staffGetMealNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$array[hallId]' and mealType = '$array[mealType]' and type in ('取餐','代取餐')",'sum'=>'num'));
                        $row[] = $staffGetMealNum;
                        break;
                    case "visitMealNum":
                        $visitMealNum = find(array('table'=>'meal_report','where'=>"hallId = '$array[hallId]'  and mealType = '$array[mealType]' and type ='申请客餐'",'sum'=>'num'));
                        $row[] = $visitMealNum;
                        break;
                    case "visitGetMealNum":
                        $visitGetMealNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$array[hallId]'  and mealType = '$array[mealType]' and type ='客餐取餐'",'sum'=>'num'));
                        $row[] = $visitGetMealNum;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='abolishedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 导出
     */
    public function exportFoodData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power('foodStatistics', 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $tr = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = [];
            }else{
                $sql = static::rGet(self::$stid.self::page.'foodSql');
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $visitMealNum = find(array('table'=>'meal_report','where'=>"hallId = '$array[hallId]'  and mealType = '$array[mealType]' and type ='申请客餐'",'sum'=>'num'));
                $visitGetMealNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$array[hallId]'  and mealType = '$array[mealType]' and type ='客餐取餐'",'sum'=>'num'));
                $hall = query('dining_hall',"id = '$array[hallId]'");
                $staffMealNum = find(array('table'=>'meal_report','where'=>"hallId = '$array[hallId]' and mealType = '$array[mealType]' and type in ('报餐','代报餐')",'sum'=>'num'));
                $staffGetMealNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$array[hallId]' and mealType = '$array[mealType]' and type in ('取餐','代取餐')",'sum'=>'num'));
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '食堂名称'=>$hall['name'],
                            '餐别'=>$array['mealType'],
                            '员工报餐份数'=>$staffMealNum,
                            '员工取餐份数'=>$staffGetMealNum,
                            '客餐申请份数'=>$visitMealNum,
                            '客餐取餐份数'=>$visitGetMealNum,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了按餐汇总报餐取餐记录";
            $this->logText(["type" => 'foodStatistics', "text" => $text]);
            $this->excelOut($title, $tr, "按餐汇总报餐取餐记录.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*详情页*/
    public function detail()
    {
        $source = $this->get('source');
        $recordDate = $this->get('recordDate');
        $staffId = $this->get('staffId');
        $hallId = $this->get('hallId');
        $mealType = $this->get('mealType');
        if (empty($source)) {
            $html = '未找到来源';
        } else {

            //菜单
            $data = array(
                "id" => '',
            );
            $tr[] = ['日期', '食堂名称', '餐别', '报餐类型', '员工', '份数', '报餐人', '报餐时间', '取餐类型', '份数', '取餐人','取餐时间'];
            $totalAskNum = $totalTakeNum=0;
            if ($source =='报餐取餐'){
                $totalAskNum = find(array('table'=>'meal_report','where'=>"hallId = '$hallId' and recordDate = '$recordDate' and mealType = '$mealType'",'sum'=>'num'));
                $totalTakeNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$hallId' and recordDate = '$recordDate' and mealType = '$mealType'",'sum'=>'num'));
                $result = find(array('table' =>'meal_report', 'where' => "hallId = '$hallId' and recordDate = '$recordDate' and mealType = '$mealType' order by time asc"));
                static::rSet(self::$stid.self::page.'detailSql', $result['sql'], 3600*5);
                foreach ($result['array'] as $array) {
                    $hall = query('dining_hall',"id = '$array[hallId]'");
                    $takeMeal = query('meal_take_record',"reportId = '$array[id]'");
                    $tr[] = [
                        $array['recordDate'],
                        $hall['name'],
                        $array['mealType'],
                        $array['type'],
                        self::findStaff($array['staffId']),
                        $array['num'],
                        self::findStaff($array['stid']),
                        $array['time'],
                        $takeMeal['type'],
                        $takeMeal['num'],
                        self::findStaff($takeMeal['staffId']),
                        $takeMeal['time'],
                    ];
                }
            }elseif($source =='按人汇总'){
                $totalAskNum = find(array('table'=>'meal_report','where'=>"hallId = '$hallId' and staffId = '$staffId' and mealType = '$mealType'",'sum'=>'num'));
                $totalTakeNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$hallId' and staffId = '$staffId' and mealType = '$mealType'",'sum'=>'num'));
                $result = find(array('table' =>'meal_report', 'where' => "hallId = '$hallId' and staffId = '$staffId' and mealType = '$mealType' order by time asc"));
                static::rSet(self::$stid.self::page.'detailSql', $result['sql'], 3600*5);
                foreach ($result['array'] as $array) {
                    $hall = query('dining_hall',"id = '$array[hallId]'");
                    $takeMeal = query('meal_take_record',"reportId = '$array[id]'");
                    $tr[] = [
                        $array['recordDate'],
                        $hall['name'],
                        $array['mealType'],
                        $array['type'],
                        self::findStaff($array['staffId']),
                        $array['num'],
                        self::findStaff($array['stid']),
                        $array['time'],
                        $takeMeal['type'],
                        $takeMeal['num'],
                        self::findStaff($takeMeal['staffId']),
                        $takeMeal['time'],
                    ];
                }
            }elseif($source =='按餐汇总'){
                $totalAskNum = find(array('table'=>'meal_report','where'=>"hallId = '$hallId' and mealType = '$mealType'",'sum'=>'num'));
                $totalTakeNum = find(array('table'=>'meal_take_record','where'=>"hallId = '$hallId' and mealType = '$mealType'",'sum'=>'num'));
                $result = find(array('table' =>'meal_report', 'where' => "hallId = '$hallId' and mealType = '$mealType' order by time asc"));
                static::rSet(self::$stid.self::page.'detailSql', $result['sql'], 3600*5);
                foreach ($result['array'] as $array) {
                    $hall = query('dining_hall',"id = '$array[hallId]'");
                    $takeMeal = query('meal_take_record',"reportId = '$array[id]'");
                    $tr[] = [
                        $array['recordDate'],
                        $hall['name'],
                        $array['mealType'],
                        $array['type'],
                        self::findStaff($array['staffId']),
                        $array['num'],
                        self::findStaff($array['stid']),
                        $array['time'],
                        $takeMeal['type'],
                        $takeMeal['num'],
                        self::findStaff($takeMeal['staffId']),
                        $takeMeal['time'],
                    ];
                }
            }
            $total_tr = [
                5 => $totalAskNum,
                9 => $totalTakeNum,
            ];
            $exportBtn = '';
            if($this->power(self::page,'export')){
                $exportBtn .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportDetailData'><span class='spanButton'>导出</span></a>\n";
            }
            //按钮
            //生成表单
            $data['button'] = $exportBtn;
            $data['html'] = $this->detailList([
                'html' => $this->listTable(array('tr' => $tr, 'total' => $total_tr, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
    /**
     * 导出明细
     */
    #[NoReturn] public function exportDetailData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $sql = static::rGet(self::$stid.self::page.'detailSql');
            $title =  array('日期', '食堂名称', '餐别', '报餐类型', '员工', '份数', '报餐人', '报餐时间', '取餐类型', '份数', '取餐人','取餐时间');
            $result['array'] =  sqlFind($sql);
            if (is_array($result['array'])) {
                foreach ($result['array'] as $array) {
                    $hall = query('dining_hall',"id = '$array[hallId]'");
                    $takeMeal = query('meal_take_record',"reportId = '$array[id]'");
                    $tr[] = [
                        $array['recordDate'],
                        $hall['name'],
                        $array['mealType'],
                        $array['type'],
                        self::findStaff($array['staffId']),
                        $array['num'],
                        self::findStaff($array['stid']),
                        $array['time'],
                        $takeMeal['type'],
                        $takeMeal['num'],
                        self::findStaff($takeMeal['staffId']),
                        $takeMeal['time'],
                    ];
                }
            }
            $text = $this->control['name'] . "导出了报餐取餐明细记录";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, "按人汇总报餐取餐明细记录.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            '按餐汇总'=>[
                [
                    'columnName'=>'食堂名称',
                    'aliasName'=>'食堂名称',
                ],
                [
                    'columnName'=>'餐别',
                    'aliasName'=>'餐别',
                ],
                [
                    'columnName'=>'员工报餐份数',
                    'aliasName'=>'员工报餐份数',
                ],
                [
                    'columnName'=>'员工取餐份数',
                    'aliasName'=>'员工取餐份数',
                ],
                [
                    'columnName'=>'客餐申请份数',
                    'aliasName'=>'客餐申请份数',
                ],
                [
                    'columnName'=>'客餐取餐份数',
                    'aliasName'=>'客餐取餐份数',
                ],
            ],
            '按人汇总'=>[
                [
                    'columnName'=>'部门',
                    'aliasName'=>'部门',
                ],
                [
                    'columnName'=>'员工',
                    'aliasName'=>'员工',
                ],
                [
                    'columnName'=>'食堂名称',
                    'aliasName'=>'食堂名称',
                ],
                [
                    'columnName'=>'餐别',
                    'aliasName'=>'餐别',
                ],
                [
                    'columnName'=>'报餐份数',
                    'aliasName'=>'报餐份数',
                ],
                [
                    'columnName'=>'取餐份数',
                    'aliasName'=>'取餐份数',
                ],
                [
                    'columnName'=>'差异份数',
                    'aliasName'=>'差异份数',
                ],
            ],
            default=>  [
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                ],
                [
                    'columnName'=>'食堂名称',
                    'aliasName'=>'食堂名称',
                ],
                [
                    'columnName'=>'餐别',
                    'aliasName'=>'餐别',
                ],
                [
                    'columnName'=>'员工报餐份数',
                    'aliasName'=>'员工报餐份数',
                ],
                [
                    'columnName'=>'菜品明细',
                    'aliasName'=>'菜品明细',
                ],
                [
                    'columnName'=>'员工取餐份数',
                    'aliasName'=>'员工取餐份数',
                ],
                [
                    'columnName'=>'客餐申请份数',
                    'aliasName'=>'客餐申请份数',
                ],
                [
                    'columnName'=>'客餐取餐份数',
                    'aliasName'=>'客餐取餐份数',
                ],
            ]
        };
    }
}
